/* spi通信调用函数  */
#include "w25q128.h"

static struct rt_spi_device *spi_dev_w25q = RT_NULL;
static uint8_t spi_buffer[260] = {0};        // SPI传输缓冲区

/**
 * Check if SPI device is initialized
 */
bool w25q_is_initialized(void)
{
    return (spi_dev_w25q != RT_NULL);
}

/**
 * Low-level SPI transfer with error checking
 */
static rt_err_t w25q_spi_transfer(const uint8_t *send_buf, uint8_t *recv_buf, size_t length)
{
    rt_err_t result = RT_EOK;
    struct rt_spi_message msg;
    struct rt_spi_message *msg_result;

    if (!w25q_is_initialized()) {
        LOG_E("SPI device not initialized!");
        return -RT_ERROR;
    }

    /* Clear receive buffer before transfer */
    if (recv_buf) {
        rt_memset(recv_buf, 0, length);
    }

    /* Prepare SPI message */
    msg.send_buf = send_buf;
    msg.recv_buf = recv_buf;
    msg.length = length;
    msg.cs_take = 0;
    msg.cs_release = 0;
    msg.next = RT_NULL;

    /* Perform SPI transfer */
    msg_result = rt_spi_transfer_message(spi_dev_w25q, &msg);

    if (msg_result != RT_NULL) {
        LOG_E("SPI transfer failed, incomplete message");
        result = -RT_ERROR;
    }

    return result;
}

/**
 * Attach SPI device to bus
 */
static rt_err_t w25q_spi_attach(void)
{
    rt_err_t result = RT_EOK;
    struct rt_spi_bus *bus = (struct rt_spi_bus *)rt_device_find(W25Q_SPI_BUS_NAME);

    if (!bus) {
        LOG_E("SPI bus %s not found!", W25Q_SPI_BUS_NAME);
        return -RT_ERROR;
    }

    if (spi_dev_w25q == RT_NULL) {
        spi_dev_w25q = (struct rt_spi_device *)rt_malloc(sizeof(struct rt_spi_device));
        if (!spi_dev_w25q) {
            LOG_E("Failed to allocate SPI device memory!");
            return -RT_ENOMEM;
        }
    }
    /*result = rt_spi_bus_attach_device(spi_dev_w25q, W25Q_SPI_DEVICE_NAME,
                                          W25Q_SPI_BUS_NAME, (void *)W25Q_CS_PIN);*/

    result= rt_spi_bus_attach_device_cspin(spi_dev_w25q, W25Q_SPI_DEVICE_NAME,
            W25Q_SPI_BUS_NAME,W25Q_CS_PIN,RT_NULL);
    if (result != RT_EOK) {
        LOG_E("Failed to attach device %s to bus %s, error code: %d",
              W25Q_SPI_DEVICE_NAME, W25Q_SPI_BUS_NAME, result);
        if (spi_dev_w25q) {
            rt_free(spi_dev_w25q);
            spi_dev_w25q = RT_NULL;
        }
    } else {
        LOG_I("Device %s attached to bus %s successfully",
              W25Q_SPI_DEVICE_NAME, W25Q_SPI_BUS_NAME);
    }

    return result;
}

extern void cmd_load_all_data();
/**
 * Initialize W25Q128 SPI Flash
 */
int w25q_spi_init(void)  // 修改：返回类型改为int
{
    rt_err_t ret = RT_EOK;
    struct rt_spi_configuration cfg;

    if (w25q_is_initialized()) {
        LOG_I("W25Q128 already initialized!");
        return RT_EOK;
    }

    ret = w25q_spi_attach();
    if (ret != RT_EOK) {
        LOG_E("SPI device attachment failed!");
        return ret;
    }

    spi_dev_w25q = (struct rt_spi_device *)rt_device_find(W25Q_SPI_DEVICE_NAME);
    if (!spi_dev_w25q) {
        LOG_E("Can't find %s device after attachment!", W25Q_SPI_DEVICE_NAME);
        return -RT_ERROR;
    }

    cfg.data_width = 8;
    cfg.mode = RT_SPI_MASTER | RT_SPI_MODE_0 | RT_SPI_MSB;
    cfg.max_hz = 10 * 1000 * 1000;

    ret = rt_spi_configure(spi_dev_w25q, &cfg);
    if (ret != RT_EOK) {
        LOG_E("SPI device configuration failed, error code: %d", ret);
        return ret;
    }
    LOG_I("W25Q128 initialization successful!");
    //装载全部数据
    cmd_load_all_data();
    rt_thread_mdelay(500);
    //装启动去读
   cmd_start_storage();
    rt_thread_mdelay(100);
    return RT_EOK;
}

/**
 * 向W25Q128写入数据（带自动擦除功能）
 * @param address 写入地址（需4KB对齐）
 * @param data 待写入的数据缓冲区
 * @param length 数据长度（不能超过扇区大小4096字节）
 * @return RT_EOK 成功，其他值 失败
 */
rt_err_t w25q_write_data_with_erase(uint32_t address, const uint8_t *data, size_t length)
{
    rt_err_t result = RT_EOK;

    if (!data || length == 0 || length > 4096) {
        LOG_E("Invalid write parameters!");
        return -RT_ERROR;
    }

    if (!w25q_is_initialized()) {
        LOG_E("SPI device not initialized!");
        return -RT_ERROR;
    }

    /* 计算扇区地址（确保4KB对齐） */
    uint32_t sector_address = address & 0xFFFFF000;

    result = w25q_erase_sector(sector_address);
    if (result != RT_EOK) {
        LOG_E("Sector erase failed! Error code: %d", result);
        return result;
    }

    /* 2. 写入数据（按页写入，页大小256字节） */
    size_t bytes_written = 0;
    while (bytes_written < length) {
        size_t page_offset = address % 256;
        size_t page_remaining = 256 - page_offset;
        size_t bytes_to_write = (length - bytes_written) < page_remaining ?
                               (length - bytes_written) : page_remaining;

        result = w25q_write_data(address, data + bytes_written, bytes_to_write);
        if (result != RT_EOK) {
            LOG_E("Page write failed at offset %d! Error code: %d", bytes_written, result);
            return result;
        }

        bytes_written += bytes_to_write;
        address += bytes_to_write;

        /* 短延时确保安全 */
        rt_thread_mdelay(1);
    }

    return RT_EOK;
}

/**
 * Read W25Q128 status register
 */
rt_err_t w25q_read_status(uint8_t *status)
{
    if (!status || !w25q_is_initialized()) {
        return -RT_ERROR;
    }

    spi_buffer[0] = W25X_READ_STATUS_REG1;

    return w25q_spi_transfer(spi_buffer, spi_buffer, 2);
}

/**
 * Send write enable command
 */
rt_err_t w25q_write_enable(void)
{
    spi_buffer[0] = W25X_WRITE_ENABLE;
    return w25q_spi_transfer(spi_buffer, NULL, 1);
}

/**
 * Read W25Q128 JEDEC ID
 * @return RT_EOK on success, error code on failure
 */
rt_err_t w25q_read_id(uint8_t *manufacturer_id, uint16_t *device_id)
{
    rt_err_t result = RT_EOK;

    /* Send JEDEC ID command */
    spi_buffer[0] = W25X_JEDEC_ID;

    rt_pin_write(W25Q_CS_PIN, false);
    /* Perform command transfer */
    result = w25q_spi_transfer(spi_buffer, NULL, 1);
    if (result != RT_EOK) {
        LOG_E("Failed to send JEDEC ID command!");
        return result;
    }

    /* Small delay before reading response */
    rt_thread_mdelay(1);

    /* Read 3-byte response */
    result = w25q_spi_transfer(NULL, spi_buffer, 3);
    if (result != RT_EOK) {
        LOG_E("Failed to read JEDEC ID response!");
        return result;
    }
    rt_pin_write(W25Q_CS_PIN, true);
    /* Parse JEDEC ID */
    if (manufacturer_id)
        *manufacturer_id = spi_buffer[0];  // Manufacturer ID

    if (device_id)
        *device_id = (spi_buffer[1] << 8) | spi_buffer[2];  // Device ID

    LOG_D("JEDEC ID response: 0x%02X 0x%02X 0x%02X",
          spi_buffer[0], spi_buffer[1], spi_buffer[2]);

    return RT_EOK;
}

/**
 * Thread for continuous ID reading
 */
static void continuous_id_read_thread(void *parameter)
{
    uint8_t manufacturer_id;
    uint16_t device_id;
    rt_err_t result;

    /* Wait for device initialization */
    rt_thread_mdelay(4000);

    if (!w25q_is_initialized()) {
        LOG_E("SPI device not initialized!");
        return;
    }

    rt_kprintf("\n=== Continuous ID Reading Started ===\n");
    rt_kprintf("Press Ctrl+C to stop\n\n");

    while (1) {
        rt_pin_write(W25Q_CS_PIN, false);
        rt_thread_mdelay(100);
        result = w25q_read_id(&manufacturer_id, &device_id);
        if (result == RT_EOK) {
            LOG_I("ID Read Success: Manufacturer=0x%02X, Device=0x%04X",
                  manufacturer_id, device_id);
            // 从扇区读取数据
            uint8_t read_data[10];
            w25q_read_data(0x00000000, read_data, sizeof(read_data));
        } else {
            LOG_E("ID Read Failed!");
        }
        rt_pin_write(W25Q_CS_PIN, true);
        /* 500ms delay between readings for oscilloscope observation */
        rt_thread_mdelay(500);
    }
}

void cmd_id_read(void *parameter)  // 修改：移除static关键字
{
    uint8_t manufacturer_id;
    uint16_t device_id;
    rt_err_t result;
    /* Wait for device initialization */
    if (!w25q_is_initialized()) {
        LOG_E("SPI device not initialized!");
        return;
    }
    rt_kprintf("\n= ID Reading Started =\n");
    for(int i=0;i<2;i++){
    rt_thread_mdelay(500);
    result = w25q_read_id(&manufacturer_id, &device_id);
    if(i==1){
    if (result == RT_EOK) {
          LOG_I("ID Read Success: Manufacturer=0x%02X, Device=0x%04X\r\n",
                  manufacturer_id, device_id);            // 从扇区读取数据
    } else {
       LOG_E("ID Read Failed!");
    }
    }
    rt_thread_mdelay(500);
    }
}

void read_test(void *parameter)  // 修改：移除static关键字
{
    // 从扇区读取数据
   uint8_t read_data[10];
   w25q_read_data(0x00000000, read_data, sizeof(read_data));
   for (int i = 0; i < sizeof(read_data)/sizeof(read_data[0]); i++) {
       rt_kprintf("%02X ", read_data[i]);
   }
}

void erase_test(void *parameter)  // 修改：移除static关键字
{
    uint8_t read_data[10];
    rt_err_t result;
    // 扇区地址，这里假设为0x00000000，需根据实际情况确保4KB对齐
    uint32_t sector_address = 0x00000000;
    // 擦除扇区
    result = w25q_erase_sector(sector_address);
    if (result != RT_EOK) {
        rt_kprintf("Sector erase failed! Error code: %d\n", result);
        return;
    }

    // 从扇区读取数据
    result = w25q_read_data(sector_address, read_data, sizeof(read_data));
    if (result != RT_EOK) {
        rt_kprintf("Read data failed! Error code: %d\n", result);
        return;
    }

    for (int i = 0; i < sizeof(read_data)/sizeof(read_data[0]); i++) {
        rt_kprintf("%02X ", read_data[i]);
    }
    rt_kprintf("\n");
}

/**
 * MSH command to start continuous ID reading
 */
void cmd_id(int argc, char *argv[])  // 修改：移除static关键字
{
    static rt_thread_t tid = RT_NULL;

    if (tid == RT_NULL) {
        tid = rt_thread_create("id_reader",
                              continuous_id_read_thread,
                              RT_NULL,
                              1024,
                              25,
                              10);
        if (tid != RT_NULL) {
            rt_thread_startup(tid);
            rt_kprintf("Continuous ID reading started...\n");
        } else {
            rt_kprintf("Failed to create ID reader thread!\n");
        }
    } else {
        rt_kprintf("Continuous ID reading is already running!\n");
    }
}

/**
 * @param length 数据长度，
 * 向 W25Q128 写入数据（页编程）
 * @param address 写入地址，必须是页对齐的（256字节页大小）
 * @param data 待写入的数据缓冲区不能超过页大小（256字节）
 * @return RT_EOK 成功，其他值 失败
 */
rt_err_t w25q_write_data(uint32_t address, const uint8_t *data, size_t length)
{
rt_err_t result = RT_EOK;
uint8_t status;

if (!data || length == 0 || length > 256) {
    rt_kprintf("Invalid write parameters!");
    return -RT_ERROR;
}

if (!w25q_is_initialized()) {
    rt_kprintf("SPI device not initialized!");
    return -RT_ERROR;
}

/* 检查非易失性存储器是否忙 */
result = w25q_read_status(&status);
if (result != RT_EOK) {
    rt_kprintf("Failed to read status register!");
    return result;
}

if (status & 0x01) {  // BUSY位
    rt_kprintf("Device is busy!");
    return -RT_EBUSY;
}

/* 发送写使能命令 */
rt_pin_write(W25Q_CS_PIN, PIN_LOW);
result = w25q_write_enable();
rt_pin_write(W25Q_CS_PIN, PIN_HIGH);
if (result != RT_EOK) {
    rt_kprintf("Failed to enable write!");
    return result;
}

/* 准备写命令和地址 */
spi_buffer[0] = 0x02;  // 页编程命令
spi_buffer[1] = (address >> 16) & 0xFF;  // 地址高字节
spi_buffer[2] = (address >> 8) & 0xFF;   // 地址中字节
spi_buffer[3] = address & 0xFF;          // 地址低字节

/* 复制数据到发送缓冲区 */
rt_memcpy(&spi_buffer[4], data, length);

/* 执行SPI传输（带CS控制） */
rt_pin_write(W25Q_CS_PIN, PIN_LOW);
result = w25q_spi_transfer(spi_buffer, NULL, 4 + length);
rt_pin_write(W25Q_CS_PIN, PIN_HIGH);

if (result != RT_EOK) {
    rt_kprintf("SPI write transfer failed!");
    return result;
}

/* 等待写入完成 */
do {
    rt_thread_mdelay(1);
    result = w25q_read_status(&status);
    if (result != RT_EOK) {
        rt_kprintf("Failed to read status register during write!");
        return result;
    }
} while (status & 0x01);

return RT_EOK;
}

/**
 * 从 W25Q128 读取数据
 * @param address 读取起始地址
 * @param data 数据接收缓冲区
 * @param length 要读取的数据长度
 * @return RT_EOK 成功，其他值 失败
 */
rt_err_t w25q_read_data(uint32_t address, uint8_t *data, size_t length)
{
    rt_err_t result = RT_EOK;
    uint8_t status;

    if (!data || length == 0) {
        rt_kprintf("Invalid read parameters!");
        return -RT_ERROR;
    }

    if (!w25q_is_initialized()) {
        rt_kprintf("SPI device not initialized!");
        return -RT_ERROR;
    }

    /* 检查非易失性存储器是否忙 */
    result = w25q_read_status(&status);
    if (result != RT_EOK) {
        rt_kprintf("Failed to read status register!");
        return result;
    }

    if (status & 0x01) {  // BUSY位
        rt_kprintf("Device is busy!");
        return -RT_EBUSY;
    }

    /* 准备读命令和地址 */
    spi_buffer[0] = 0x03;  // 读取数据命令
    spi_buffer[1] = (address >> 16) & 0xFF;  // 地址高字节
    spi_buffer[2] = (address >> 8) & 0xFF;   // 地址中字节
    spi_buffer[3] = address & 0xFF;          // 地址低字节

    /* 执行SPI传输（带CS控制） */
    rt_pin_write(W25Q_CS_PIN, PIN_LOW);

    /* 发送命令和地址 */
    result = w25q_spi_transfer(spi_buffer, NULL, 4);
    if (result != RT_EOK) {
        rt_kprintf("Failed to send read command!");
        rt_pin_write(W25Q_CS_PIN, PIN_HIGH);
        return result;
    }

    /* 读取数据 */
    result = w25q_spi_transfer(NULL, data, length);
    rt_pin_write(W25Q_CS_PIN, PIN_HIGH);

    if (result != RT_EOK) {
        rt_kprintf("SPI read transfer failed!");
        return result;
    }
    return RT_EOK;
}

/**
 * 擦除 W25Q128 的扇区（4KB）
 * @param sector_address 扇区地址，必须是4KB对齐的
 * @return RT_EOK 成功，其他值 失败
 */
rt_err_t w25q_erase_sector(uint32_t sector_address)
{
    rt_err_t result = RT_EOK;
    uint8_t status;

    if (!w25q_is_initialized()) {
        LOG_E("SPI device not initialized!");
        return -RT_ERROR;
    }

    /* 检查地址是否4KB对齐 */
    if (sector_address % 4096 != 0) {
        LOG_E("Sector address must be 4KB aligned!");
        return -RT_ERROR;
    }

    /* 检查非易失性存储器是否忙 */
    result = w25q_read_status(&status);
    if (result != RT_EOK) {
        LOG_E("Failed to read status register!");
        return result;
    }

    if (status & 0x01) {  // BUSY位
        LOG_E("Device is busy!");
        return -RT_EBUSY;
    }
    /* 发送写使能命令 */
    rt_pin_write(W25Q_CS_PIN, PIN_LOW);
    result = w25q_write_enable();
    rt_pin_write(W25Q_CS_PIN, PIN_HIGH);
    if (result != RT_EOK) {
        LOG_E("Failed to enable write!");
        return result;
    }

    /* 准备扇区擦除命令和地址 */
    spi_buffer[0] = 0x20;  // 扇区擦除命令（4KB）
    spi_buffer[1] = (sector_address >> 16) & 0xFF;  // 地址高字节
    spi_buffer[2] = (sector_address >> 8) & 0xFF;   // 地址中字节
    spi_buffer[3] = sector_address & 0xFF;          // 地址低字节

    /* 执行SPI传输（带CS控制） */
    rt_pin_write(W25Q_CS_PIN, PIN_LOW);
    result = w25q_spi_transfer(spi_buffer, NULL, 4);
    rt_pin_write(W25Q_CS_PIN, PIN_HIGH);

    if (result != RT_EOK) {
        LOG_E("SPI erase transfer failed!");
        return result;
    }
    rt_thread_mdelay(50);
    /* 等待擦除完成（可能需要数百毫秒） */
    do {
        rt_thread_mdelay(10);  // 扇区擦除可能需要较长时间
        result = w25q_read_status(&status);
        if (result != RT_EOK) {
            LOG_E("Failed to read status register during erase!");
            return result;
        }
    } while (status & 0x01);

    return RT_EOK;
}

/**
 * 擦除整个芯片
 * @return RT_EOK 成功，其他值 失败
 */
rt_err_t w25q_chip_erase(void)
{
    rt_err_t result = RT_EOK;
    uint8_t status;

    if (!w25q_is_initialized()) {
        LOG_E("SPI device not initialized!");
        return -RT_ERROR;
    }

    /* 检查非易失性存储器是否忙 */
    result = w25q_read_status(&status);
    if (result != RT_EOK) {
        LOG_E("Failed to read status register!");
        return result;
    }

    if (status & 0x01) {  // BUSY位
        LOG_E("Device is busy!");
        return -RT_EBUSY;
    }

    /* 发送写使能命令 */
    result = w25q_write_enable();
    if (result != RT_EOK) {
        LOG_E("Failed to enable write!");
        return result;
    }

    /* 准备芯片擦除命令 */
    spi_buffer[0] = 0xC7;  // 芯片擦除命令

    /* 执行SPI传输（带CS控制） */
    rt_pin_write(W25Q_CS_PIN, PIN_LOW);
    result = w25q_spi_transfer(spi_buffer, NULL, 1);
    rt_pin_write(W25Q_CS_PIN, PIN_HIGH);

    if (result != RT_EOK) {
        LOG_E("SPI chip erase transfer failed!");
        return result;
    }

    do {
        rt_thread_mdelay(100);  // 芯片擦除需要很长时间
        result = w25q_read_status(&status);
        if (result != RT_EOK) {
            LOG_E("Failed to read status register during chip erase!");
            return result;
        }
    } while (status & 0x01);

    return RT_EOK;
}

#define TEST_ADDR         0x00000000  // 测试地址，需4KB对齐
#define TEST_DATA_SIZE    16          // 测试数据大小
#define READ_WRITE_DELAY  5000        // 读写间隔5000ms

/* 测试数据缓冲区 */
static uint8_t write_data[TEST_DATA_SIZE] = {0};
static uint8_t read_data[TEST_DATA_SIZE] = {0};

/**
 * 初始化测试数据
 */
static void init_test_data(void)
{
    rt_uint32_t i;
    rt_uint32_t time = rt_tick_get();

    /* 生成随机测试数据，使用当前时间作为种子 */
    for (i = 0; i < TEST_DATA_SIZE; i++) {
        write_data[i] = (time + i) & 0xFF;
    }

    for (i = 0; i < TEST_DATA_SIZE; i++) {
        rt_kprintf("%02X ", write_data[i]);
    }
    rt_kprintf("\n");
}

/**
 * 验证读取数据是否与写入数据一致
 * @return 0-一致，非0-不一致
 */
static int verify_data(void)
{
    int i;

    for (i = 0; i < TEST_DATA_SIZE; i++) {
        if (write_data[i] != read_data[i]) {
            rt_kprintf("Data mismatch at index %d: Write=0x%02X, Read=0x%02X\n",
                       i, write_data[i], read_data[i]);
            return -1;
        }
    }

    return 0;
}

/**
 * W25Q128周期性读写测试线程
 */
static void w25q_periodic_rw_thread(void *parameter)
{
    rt_err_t result;
    rt_uint32_t count = 0;
    uint8_t status;  // 声明status变量

    /* 等待设备初始化完成 */
    rt_thread_mdelay(2000);

    rt_kprintf("\n=== W25Q128 Periodic Read-Write Test Started ===\n");
    rt_kprintf("Test address: 0x%08X, Data size: %d bytes\n", TEST_ADDR, TEST_DATA_SIZE);
    rt_kprintf("Interval: %d ms\n\n", READ_WRITE_DELAY);

    while (1)
    {
        count++;
        rt_kprintf("--- Test Cycle %d ---\n", count);

        /* 1. 初始化测试数据 */
        init_test_data();

        /* 2. 擦除目标扇区（写入前必须确保扇区已擦除） */
        rt_kprintf("Erasing sector at 0x%08X...\n", TEST_ADDR);
        result = w25q_erase_sector(TEST_ADDR);
        if (result != RT_EOK) {
            rt_kprintf("Sector erase failed! Error code: %d\n", result);
            goto test_failed;
        }

        /* 等待擦除完成 - 增加延时 */
        rt_thread_mdelay(50); // 擦除操作可能需要几十毫秒
        do {
            result = w25q_read_status(&status);
            if (result != RT_EOK) {
                rt_kprintf("Failed to read status register after erase!\n");
                goto test_failed;
            }
        } while (status & 0x01); // 等待BUSY位清零

        /* 3. 写入测试数据 */
        rt_kprintf("Writing data to 0x%08X...\n", TEST_ADDR);
        result = w25q_write_data(TEST_ADDR, write_data, TEST_DATA_SIZE);
        if (result != RT_EOK) {
            rt_kprintf("Write failed! Error code: %d\n", result);
            goto test_failed;
        }

        /* 4. 读取数据 */
        rt_kprintf("Reading data from 0x%08X...\n", TEST_ADDR);
        result = w25q_read_data(TEST_ADDR, read_data, TEST_DATA_SIZE);
        if (result != RT_EOK) {
            rt_kprintf("Read failed! Error code: %d\n", result);
            goto test_failed;
        }

        /* 5. 验证数据 - 改进验证逻辑 */
        rt_kprintf("Verifying data...\n");
        if (verify_data() == 0) {
            rt_kprintf("Data verification successful!\n");
        } else {
            rt_kprintf("Data verification failed!\n");
            /* 打印详细的验证错误信息 */
            for (int i = 0; i < TEST_DATA_SIZE; i++) {
                if (read_data[i] != write_data[i]) {
                    rt_kprintf("Mismatch at offset %d: expected 0x%02X, got 0x%02X\n",
                              i, write_data[i], read_data[i]);
                    break; // 只打印第一个不匹配，避免刷屏
                }
            }
            goto test_failed;
        }

        rt_kprintf("Test cycle %d completed successfully!\n\n", count);

        /* 等待下一次测试 - 移到成功分支 */
        rt_kprintf("Next test in %d ms...\n\n", READ_WRITE_DELAY);
        rt_thread_mdelay(READ_WRITE_DELAY);
        continue;

    test_failed:
        /* 错误恢复 - 移除未定义的w25q_reset_device() */
        rt_kprintf("SPI operation failed, resetting CS pin...\n");
        rt_pin_write(W25Q_CS_PIN, PIN_HIGH); // 确保CS引脚处于高电平

        /* 等待下一次测试 */
        rt_kprintf("Next test in %d ms...\n\n", READ_WRITE_DELAY);
        rt_thread_mdelay(READ_WRITE_DELAY);
        continue;
    }
}

/**
 * 启动周期性读写测试的MSH命令
 */
void cmd_w25q_rw_test(int argc, char *argv[])  // 修改：移除static关键字
{
    static rt_thread_t tid = RT_NULL;

    if (tid == RT_NULL) {
        /* 先确保W25Q128已初始化 */
        if (w25q_spi_init() != RT_EOK) {
            rt_kprintf("W25Q128 initialization failed!\n");
            return;
        }

        /* 创建周期性读写测试线程 */
        tid = rt_thread_create("w25q_rw",
                              w25q_periodic_rw_thread,
                              RT_NULL,
                              2048,
                              24,
                              10);
        if (tid != RT_NULL) {
            rt_thread_startup(tid);
            rt_kprintf("W25Q128 periodic read-write test started...\n");
        } else {
            rt_kprintf("Failed to create test thread!\n");
        }
    } else {
        rt_kprintf("Test is already running!\n");
    }
}

void write_read(){
/* 测试数据 */
uint8_t test_data[10] = {0x21, 0x02, 0x43};

/* 写入地址（必须4KB对齐） */
uint32_t write_address = 0x00000000;
rt_pin_write(W25Q_CS_PIN, false);
/* 执行写入 */
rt_err_t result = w25q_write_data_with_erase(write_address, test_data, sizeof(test_data));
if (result == RT_EOK) {
} else {
    rt_kprintf("Write operation failed!");
}
// 从扇区读取数据
uint8_t read_data[10];
w25q_read_data(0x00000000, read_data, sizeof(read_data));
rt_pin_write(W25Q_CS_PIN, true);
for (int i = 0; i < sizeof(read_data)/sizeof(read_data[0]); i++) {
   rt_kprintf("%02X ", read_data[i]);
}
}

/* 导出MSH命令 */
/* 可选：自动初始化（如果需要） */
MSH_CMD_EXPORT(cmd_id, Start continuous JEDEC ID reading);
MSH_CMD_EXPORT(cmd_id_read, Start continuous JEDEC ID reading);
INIT_DEVICE_EXPORT(w25q_spi_init);
// 移除错误的INIT_DEVICE_EXPORT(cmd_id_read);
